package com.hntest.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hntest.entity.LoginInfo;
import com.hntest.service.SystemDictionaryItemService;
import com.hntest.service.UserFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hntest.entity.JSONResult;
import com.hntest.entity.SystemDictionaryItem;
import com.hntest.entity.UserFile;
import com.hntest.util.UploadUtil;

@Controller("uploadController")
public class UploadController {

    private List<UserFile> userFiles = new ArrayList<>();

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private SystemDictionaryItemService systemDictionaryItemService;
	@RequestMapping("userFile")
	public String userFile(Model model, HttpServletRequest request) {
	     //根据当前用户ID查询所有关联的风控资料fileType_id is NULL
//		List<UserFile> userFiles = this.userFileService.listFilesByHasType(
//				UserContext.getCurrent().getId(), false);

        HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");

         userFiles = userFileService.selectById(currUser.getLid(),false);

        // 有没有选择的用户
        // 文件类型,设置数据字典,并往userFiles_commit
			if (this.userFiles.size() > 0) {
				/*//从数据库中查询所有编码为"userFileType"的数据字典明细
				model.addAttribute("fileTypes",
						this.systemDictionaryService.listByParentSn("userFileType"));*/
                model.addAttribute("fileTypes",
                        this.systemDictionaryItemService.selectByParentId(6));
				/////////以下为模拟数据///////////
				/*List<SystemDictionaryItem> fileTypes=new ArrayList<SystemDictionaryItem>();
				SystemDictionaryItem ft1=new SystemDictionaryItem();

				ft1.setId((long)12);
				ft1.setTitle("房产证正面");
				SystemDictionaryItem ft2=new SystemDictionaryItem();
				ft2.setId((long)13);
				ft2.setTitle("房产证反面");
				SystemDictionaryItem ft3=new SystemDictionaryItem();
				ft3.setId((long)14);
				ft3.setTitle("户口本");
				fileTypes.add(ft1);fileTypes.add(ft2);fileTypes.add(ft3);*/
				//////////////////////////////////
				model.addAttribute("userFiles", this.userFiles);//提供材料类型列表，作下拉选择
				return "userFiles_commit";
			} else {
					/*// 选择所有该用户的原有风控文件fileType_id is NOT NULL
					userFiles = this.userFileService.listFilesByHasType(UserContext
							.getCurrent().getId(), true);*/
					userFiles = userFileService.selectById(currUser.getLid(),true);

				     //////////////////////模拟原有数据,文件类型ID不为空/////////////
				    /*this.userFiles = new ArrayList<UserFile>();
				    UserFile f2=new UserFile();
				    f2.setId((long)12);
				    f2.setImage("/upload/e9615d8c-df6c-4feb-b13b-f4f8379429bb.jpg");
				    f2.setScore(5);
					SystemDictionaryItem fileType=new SystemDictionaryItem();
					fileType.setId((long)12);
					fileType.setTitle("房产证正面");
					f2.setFileType(fileType);
					this.userFiles.add(f2);*/
					//////////////////////////////////////////
					
					model.addAttribute("userFiles", this.userFiles);
				return "userFiles";
			}
			
		
	}
	
	/**
	 * 处理异步上传用户风控文件
	 */
	@RequestMapping("userFileUpload")
	@ResponseBody
	public void userFileUpload(MultipartFile file,HttpServletRequest request,UserFile userFile) {
		String basePath = request.getSession().getServletContext().getRealPath("/upload");
		String fileName = UploadUtil.upload(file, basePath);
		fileName = "/upload/" + fileName;
		//this.userFileService.apply(fileName);//存入数据库
        HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");
        userFile.setApplier(currUser);
        userFile.setImage(fileName);
        userFileService.insertUserFile(userFile);

	    //////////////以下数据为模拟文件类型ID为空fileType_id is NULL的情况///////////
		/*userFiles = new ArrayList<UserFile>();
		UserFile f1=new UserFile();
		f1.setId((long)12);
		f1.setImage("/upload/e9615d8c-df6c-4feb-b13b-f4f8379429bb.jpg");
		f1.setScore(5);
		userFiles.add(f1);*/
		///////////////////////////////////////////////////////////
	}
	
	/**
	 * 处理用户风控文件类型选择
	 */
	@RequestMapping("userFile_selectType")
	public String  userFileSelectType(Long[] fileType, Long[] id) {
		if (fileType != null && id != null && fileType.length == id.length) {
			//this.userFileService.batchUpdateFileType(id, fileType);
            int i =0;
            for (UserFile u :
                    userFiles) {
                u.setFileType(new SystemDictionaryItem(fileType[i]));
                i++;
                userFileService.updateUserFile(u);
            }

		}
		////////////模拟数据清空，去往用户风控文件查询页面//////
		//userFiles = new ArrayList<UserFile>();
		/////////////////////////////
		return "redirect:/userFile";
	}
	
	
	/*
	 * 接收身份证的正面和反面文件
	 */
	@RequestMapping("/doUploadNew")
	@ResponseBody
	public String realAuthUpload(MultipartFile file,HttpServletRequest request) {
		// 先得到basepath
		String basePath = request.getSession().getServletContext().getRealPath("/upload");
		String fileName = UploadUtil.upload(file, basePath);
		return "/upload/" + fileName;
	}
	
	/*@RequestMapping(value="/doUpload",method= {RequestMethod.POST})
	public String doUpload(@RequestParam MultipartFile photo,HttpServletRequest request) throws Exception
	{
		if(!photo.isEmpty()) {
			
			if(photo.getSize()>1024000){//大于1000k
				//throw new Exception("文件超过指定的大小!");
				request.setAttribute("errorInfo", "文件超过指定的大小!");
				return "upload";
			}
			//得到upload的绝对路径(upload为自创建)
			String realPath=request.getSession().getServletContext().getRealPath("/upload");
			//创建新的文件(使用的原文件名)
			File newFile=new File(realPath+File.separator+photo.getOriginalFilename());
			
			//开始上传文件
			photo.transferTo(newFile);
			//把新文件的绝对路径返回到成功页面
			request.setAttribute("path", newFile.getAbsolutePath());
		}
		return "uploadSuccess";
	}
	
	@RequestMapping(value="/doUploads",method= {RequestMethod.POST})
	public String doUploads(@RequestParam MultipartFile photo[],HttpServletRequest request) throws Exception
	{
		//得到upload的绝对路径(upload为自创建)
		String realPath=request.getSession().getServletContext().getRealPath("/upload");
		String pathAll="";//上传路径的总字符串
		for(int i=0;i<photo.length;i++)
		{
			if(!photo[i].isEmpty()) {
				
				if(photo[i].getSize()>1024000){//大于1000k
					//throw new Exception("文件超过指定的大小!");
					request.setAttribute("errorInfo", "文件超过指定的大小!");
					return "upload";
				}
				
				//创建新的文件(使用的原文件名)
				File newFile=new File(realPath+File.separator+photo[i].getOriginalFilename());
				
				//开始上传文件
				photo[i].transferTo(newFile);
				
				pathAll+=newFile.getAbsolutePath()+"<br/>";//累加总路径
				
			}
		}
		
		//把新文件的绝对路径返回到成功页面
		request.setAttribute("path", pathAll);
		return "uploadSuccess";
	}*/
	
/*	//处理本控制器的局部异常
	@ExceptionHandler(value=Exception.class)
	public String handlerException(Exception e,HttpServletRequest request) {
		request.setAttribute("exception", e);
		return "error";
	}*/

}
